package com.cgsd.heyu.presenter.user;

import android.util.Log;

import com.android.library.utils.AesUtil;
import com.android.library.utils.BeanUtils;
import com.android.library.utils.StringUtils;
import com.android.library.utils.SystemUtil;
import com.apkfuns.logutils.LogUtils;
import com.cgsd.heyu.App;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.common.CommonConfig;
import com.cgsd.heyu.common.FileTokenConfig;
import com.cgsd.heyu.common.Helper;
import com.cgsd.heyu.common.UserModeConfig;
import com.cgsd.heyu.entity.AdContentEntity;
import com.cgsd.heyu.entity.ConfigEntity;
import com.cgsd.heyu.entity.DefaultAvatarEntity;
import com.cgsd.heyu.entity.UploadTokenEntity;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.GlobalErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManager;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.ui.info.SettingActivity;
import com.cgsd.heyu.utils.DeviceUtils;
import com.google.gson.Gson;
import com.hztz.kankanzhuan.KanNewsSDK;
import com.hztz.kankanzhuan.listener.LoginCallListener;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import okhttp3.RequestBody;

/**
 * @author xiaoxing
 * 用户相关
 */
public class UserPresenter implements UserContract.Presenter {
    private UserContract.LoginView mLoginView;
    private UserContract.UpdateInfoView mUpdateInfoView;
    private UserContract.UserInfoView mUserInfoView;
    private UserContract.SettingView mSettingView;
    private UserContract.FeedBackView mFeedBackView;

    public UserPresenter(UserContract.LoginView view) {
        mLoginView = BeanUtils.checkNotNull(view);
        mLoginView.setPresenter(this);
    }

    public UserPresenter(UserContract.UpdateInfoView view) {
        mUpdateInfoView = BeanUtils.checkNotNull(view);
        mUpdateInfoView.setPresenter(this);
    }

    public UserPresenter(UserContract.UserInfoView view) {
        mUserInfoView = BeanUtils.checkNotNull(view);
        mUserInfoView.setPresenter(this);
    }

    public UserPresenter(UserContract.SettingView view) {
        mSettingView = BeanUtils.checkNotNull(view);
        mSettingView.setPresenter(this);
    }

    public UserPresenter(UserContract.FeedBackView view) {
        mFeedBackView = BeanUtils.checkNotNull(view);
        mFeedBackView.setPresenter(this);
    }

    @Override
    public void start() {

    }

    @Override
    public void userLogin(String mobile, String password,String deviceId) {
        HashMap<String, Object> data = new HashMap<>();
        String str = AesUtil.aesEncrypt(password);
        Helper.saveTokenInfo("");
        Helper.saveTokenPhpInfo("");
        data.put("userName", mobile);
        data.put("password", str);
        data.put("deviceId", deviceId);
        LogUtils.e("userLogin "+data.toString());
        RequestBody requestBody = RetrofitServiceManager.getBody(data);
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .login(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<UserModeConfig>>() {
                    @Override
                    public void onSuccess(BaseResponse<UserModeConfig> baseResponse) {
                        UserModeConfig.setUserModeConfig(baseResponse.getBizBody());
                        Helper.saveTokenInfo(baseResponse.getBizBody().accessToken);

                        if (mLoginView != null) {
                            mLoginView.loginSuccess(baseResponse.getBizBody());
                        }

                        LogUtils.e("userLogin"+baseResponse.toString());
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mLoginView != null) {
                            mLoginView.setErrorMessage(error);
                        }
                        LogUtils.e("userLogin"+error.getMessage());
                    }
                });
    }


    @Override
    public void register(String mobile, String verifyCode, String address, String interviewCode, String password) {
        HashMap<String, Object> data = new HashMap<>(3);
        data.put("mobilePrefix", "86");
        data.put("mobileNo", mobile);
        data.put("verificationCode", verifyCode);
        data.put("userType", "1");
        data.put("deviceId", SystemUtil.getAndroidID(App.getInstance()));
        data.put("deviceType", SystemUtil.getPhoneModel());
        data.put("location", address);
        data.put("recommendMemberNo", interviewCode);
        data.put("password", AesUtil.aesEncrypt(password));
        RequestBody requestBody = RetrofitServiceManager.getBody(data);
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .register(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<UserModeConfig>>() {
                    @Override
                    public void onSuccess(BaseResponse<UserModeConfig> baseResponse) {
                        UserModeConfig.setUserModeConfig(baseResponse.getBizBody());
                        Helper.saveTokenInfo(baseResponse.getBizBody().accessToken);
                        if (mLoginView != null) {
                            mLoginView.loginSuccess(baseResponse.getBizBody());
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mLoginView != null) {
                            mLoginView.setErrorMessage(error);
                        }
                    }
                });
    }

    @Override
    public void getVerificationCode(String mobile, String messageType) {
        HashMap<String, Object> data = new HashMap<>(3);
        data.put("mobilePrefix", "86");
        data.put("mobileNo", mobile);
        data.put("messageType", messageType);
        String json = new Gson().toJson(data);
        RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);
        RetrofitServiceManager.getInstance().creat(ApiService.class)
                .getPhoneCode(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                    @Override
                    public void onSuccess(BaseResponse<Void> baseResponse) {
                        if (mLoginView != null) {
                            mLoginView.codeSuccess();
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mLoginView != null) {
                            mLoginView.setErrorMessage(error);
                        }
                    }
                });
    }

    @Override
    public void updateInfo(UserModeConfig userModeConfig) {
        RequestBody requestBody = RetrofitServiceManager.getBody(userModeConfig);
        if (StringUtils.isNotEmpty(userModeConfig.gender)) {
            RetrofitServiceManager.getInstance().creat(ApiService.class)
                    .updateSex(requestBody)
                    .compose(RxjavaHelper.observeOnMainThread())
                    .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                        @Override
                        public void onSuccess(BaseResponse<Void> baseResponse) {
                            if (mUpdateInfoView != null) {
                                mUpdateInfoView.updateSexSuccess();
                            }
                        }

                        @Override
                        public void onError(ErrorMessage error) {
                            if (mUpdateInfoView != null) {
                                mUpdateInfoView.setErrorMessage(error);
                            }
                        }
                    });
        } else if (StringUtils.isNotEmpty(userModeConfig.headImgUrl)) {
            RetrofitServiceManager.getInstance().creat(ApiService.class)
                    .updateImage(requestBody)
                    .compose(RxjavaHelper.observeOnMainThread())
                    .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                        @Override
                        public void onSuccess(BaseResponse<Void> baseResponse) {
                            if (mUpdateInfoView != null) {
                                mUpdateInfoView.updateAvatarSuccess();
                            }
                        }

                        @Override
                        public void onError(ErrorMessage error) {
                            if (mUpdateInfoView != null) {
                                mUpdateInfoView.setErrorMessage(error);
                            }
                        }
                    });
        } else if (StringUtils.isNotEmpty(userModeConfig.nickName)) {
            RetrofitServiceManager.getInstance().creat(ApiService.class)
                    .updateNickName(requestBody)
                    .compose(RxjavaHelper.observeOnMainThread())
                    .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                        @Override
                        public void onSuccess(BaseResponse<Void> baseResponse) {
                            if (mUpdateInfoView != null) {
                                mUpdateInfoView.updateNickNameSuccess();
                            }
                        }

                        @Override
                        public void onError(ErrorMessage error) {
                            if (mUpdateInfoView != null) {
                                mUpdateInfoView.setErrorMessage(error);
                            }
                        }
                    });
        }

    }

    @Override
    public void getUserInfo() {
        RetrofitServiceManager.getInstance().creat(ApiService.class)
                .getUserInfo()
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<UserModeConfig>>() {
                    @Override
                    public void onSuccess(BaseResponse<UserModeConfig> baseResponse) {
                        UserModeConfig.setUserModeConfig(baseResponse.getBizBody());
                        if (mUserInfoView != null) {
                            mUserInfoView.infoSuccess(baseResponse.getBizBody());
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mUserInfoView != null) {
                            mUserInfoView.setErrorMessage(error);
                        }
                    }
                });
    }

    @Override
    public void getConfigInfo(String type, int size) {
        HashMap<String, Object> data = new HashMap<>(3);
        if (type != null) {
            data.put("sysType", type);
        }
        data.put("currentPage", 1);
        data.put("pageSize", size);
        String json = new Gson().toJson(data);
        RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);
        RetrofitServiceManager.getInstance().creat(ApiService.class)
                .getConfigInfo(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<List<ConfigEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<ConfigEntity>> baseResponse) {
                        setCommonConfig(baseResponse.getBizBody(), type);
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mSettingView != null) {
                            mSettingView.setErrorMessage(error);
                        }
                    }
                });
    }

    private void setCommonConfig(List<ConfigEntity> entities, String sysType) {
        if (BeanUtils.isEmpty(entities)) {
            return;
        }
        if (sysType == null) {
            CommonConfig.setCommonConfig(entities);
        }
        if (mUserInfoView != null) {
            mUserInfoView.setConfig(sysType);
        }
    }

    @Override
    public void uploadImage(List<String> files, List<String> keys) {
        UploadManager uploadManager = FileTokenConfig.getInstance().getUploadManager();
        UploadTokenEntity imageToken = FileTokenConfig.getInstance().imageTokenData();
        for (int i = 0; i < files.size(); i++) {
            uploadManager.put(files.get(i), keys.get(i), imageToken.token, new UpCompletionHandler() {
                @Override
                public void complete(String key, ResponseInfo info, JSONObject response) {
                    if (info.isOK()) {
                        if (mFeedBackView != null) {
                            mFeedBackView.uploadImageSuccess(key);
                        }
                    } else {
                        if (mFeedBackView != null) {
                            mFeedBackView.setErrorMessage(new ErrorMessage(GlobalErrorMessage.ErrorCode.ERROR_CODE_1002, GlobalErrorMessage.ErrorMessage.ERROR_MESSAGE_1002));
                        }
                    }

                }
            }, null);
        }
    }

    @Override
    public void uploadMultiMedia(List<String> files, List<String> keys) {

    }

    @Override
    public void feedBack(List<String> images, String content) {
        HashMap<String, Object> data = new HashMap<>(3);
        if (BeanUtils.isNotEmpty(images)) {
            data.put("imgUrls", images);
        }
        data.put("memberNo", UserModeConfig.getInstance().memberNo);
        data.put("mobileNo", UserModeConfig.getInstance().mobileNo);
        data.put("mobilePrefix", "86");
        data.put("content", content);
        String json = new Gson().toJson(data);
        RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json);
        RetrofitServiceManager.getInstance().creat(ApiService.class)
                .feedBack(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                    @Override
                    public void onSuccess(BaseResponse<Void> baseResponse) {
                        if (mFeedBackView != null) {
                            mFeedBackView.feedBackSuccess();
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mFeedBackView != null) {
                            mFeedBackView.setErrorMessage(error);
                        }
                    }
                });
    }

    @Override
    public void signOut(String type) {
        if (SettingActivity.LOGOUT.equals(type)) {
            RetrofitServiceManager.getInstance().creat(ApiService.class)
                    .logout()
                    .compose(RxjavaHelper.observeOnMainThread())
                    .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                        @Override
                        public void onSuccess(BaseResponse<Void> baseResponse) {
                            if (mSettingView != null) {
                                mSettingView.signOutSuccess(type);
                            }
                        }

                        @Override
                        public void onError(ErrorMessage error) {
                            if (mSettingView != null) {
                                mSettingView.setErrorMessage(error);
                            }
                        }
                    });
        } else {
            RetrofitServiceManager.getInstance().creat(ApiService.class)
                    .signOut()
                    .compose(RxjavaHelper.observeOnMainThread())
                    .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                        @Override
                        public void onSuccess(BaseResponse<Void> baseResponse) {
                            if (mSettingView != null) {
                                mSettingView.signOutSuccess(type);
                            }
                        }

                        @Override
                        public void onError(ErrorMessage error) {
                            if (mSettingView != null) {
                                mSettingView.setErrorMessage(error);
                            }
                        }
                    });
        }

    }

    @Override
    public void getAdContent(String type) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("locationId", type);
        RequestBody requestBody = RetrofitServiceManager.getBody(data);
        RetrofitServiceManager.getInstance().creat(ApiService.class)
                .getAdContent(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<AdContentEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<AdContentEntity> baseResponse) {
                        if (mUserInfoView != null) {
                            mUserInfoView.setAdContent(baseResponse.getBizBody());
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mUserInfoView != null) {
                            mUserInfoView.setErrorMessage(error);
                        }
                    }
                });
    }

    @Override
    public void getKeyConfig(String key) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("sysKey", key);
        RequestBody requestBody = RetrofitServiceManager.getBody(data);
        RetrofitServiceManager.getInstance().creat(ApiService.class)
                .getOtherConfig(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<ConfigEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<ConfigEntity> baseResponse) {
                        ConfigEntity entity = baseResponse.getBizBody();
                        if (entity == null) {
                            return;
                        }
                        CommonConfig.setCommonConfig(entity);
                    }

                    @Override
                    public void onError(ErrorMessage error) {

                    }
                });
    }

    @Override
    public void getDefaultAvatar() {
        RetrofitServiceManager.getInstance().creat(ApiService.class)
                .getDefaultAvatar()
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<List<DefaultAvatarEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<DefaultAvatarEntity>> baseResponse) {
                        if (mUpdateInfoView != null) {
                            mUpdateInfoView.userAvatarList(baseResponse.getBizBody());
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mUpdateInfoView != null) {
                            mUpdateInfoView.setErrorMessage(error);
                        }
                    }
                });
    }

    @Override
    public void updatePassword(String mobileNo, String password, String verificationCode) {
        HashMap<String, Object> data = new HashMap<>();
        String str = AesUtil.aesEncrypt(password);
        Helper.saveTokenInfo("");
        Helper.saveTokenPhpInfo("");
        data.put("mobileNo", mobileNo);
        data.put("password", str);
        data.put("verificationCode", verificationCode);
        RequestBody requestBody = RetrofitServiceManager.getBody(data);
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .updatePassword(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<Void>>() {
                    @Override
                    public void onSuccess(BaseResponse<Void> baseResponse) {
                        if (mLoginView != null) {
                            mLoginView.loginSuccess(null);
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        if (mLoginView != null) {
                            mLoginView.setErrorMessage(error);
                        }
                    }
                });
    }

}
